# -*- coding: utf-8 -*-
"""
    .filename
    ~~~~~~~~~~~~~~

    source: https://djangosnippets.org/snippets/1431/

    Sample usage:

        >>> base20 = BaseConverter('0123456789abcdefghij')
        >>> base20.from_decimal(1234)
        '31e'
        >>> base20.to_decimal('31e')
        1234

    :create by: lyncir
    :date: 2020-08-05 15:43:58 (+0800)
    :last modified date: 2020-08-05 15:48:33 (+0800)
    :last modified by: lyncir
"""


class BaseConverter(object):
    decimal_digits = "0123456789"

    def __init__(self, digits):
        self.digits = digits

    def from_decimal(self, i):
        return self.convert(i, self.decimal_digits, self.digits)

    def to_decimal(self, s):
        return int(self.convert(s, self.digits, self.decimal_digits))

    def convert(number, fromdigits, todigits):
        # Based on http://code.activestate.com/recipes/111286/
        if str(number)[0] == '-':
            number = str(number)[1:]
            neg = 1
        else:
            neg = 0

        # make an integer out of the number
        x = 0
        for digit in str(number):
           x = x * len(fromdigits) + fromdigits.index(digit)

        # create the result in base 'len(todigits)'
        if x == 0:
            res = todigits[0]
        else:
            res = ""
            while x > 0:
                digit = x % len(todigits)
                res = todigits[digit] + res
                x = int(x / len(todigits))
            if neg:
                res = '-' + res
        return res
    convert = staticmethod(convert)


# 使用不易混淆的字母对decimal进行编码和解码
base24 = BaseConverter('ZAC2B3EF4GH5TK67P8RS9WXY')
